package com.dana.judge.service.impl;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.date.StopWatch;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.core.constants.Constants;
import com.core.constants.JudgeConstants;
import com.core.enums.CodeRunStatus;
import com.dana.judge.callback.DockerStartResultCallback;
import com.dana.judge.callback.StatisticsCallback;
import com.dana.judge.config.DockerSandBoxPool;
import com.dana.judge.domain.CompileResult;
import com.dana.judge.domain.SandBoxExecuteResult;
import com.dana.judge.service.ISandboxPoolService;
import com.dana.judge.service.ISandboxService;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.*;
import com.github.dockerjava.api.model.Bind;
import com.github.dockerjava.api.model.HostConfig;
import com.github.dockerjava.api.model.Image;
import com.github.dockerjava.api.model.Volume;
import com.github.dockerjava.core.DefaultDockerClientConfig;
import com.github.dockerjava.core.DockerClientBuilder;
import com.github.dockerjava.netty.NettyDockerCmdExecFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class SandboxPoolServiceImpl implements ISandboxPoolService{

    @Autowired
    private DockerSandBoxPool dockerSandBoxPool;
    @Autowired
    private DockerClient dockerClient;

    private String containerId;

    private String userCodeFileName;


    @Value("${sandbox.limit.time:5}")
    private Long timeLimit;
    @Override
    public SandBoxExecuteResult exeJavaCode(Long uerId, String userCode, List<String> inputList) {
        //生成一个文件,存放用户提交的代码,使用docker运行,本地文件可以通过挂载数据卷的方式从宿主机传递给docker
        containerId = dockerSandBoxPool.getContainer();
        createUserCodeFile(userCode);

        //编译
        CompileResult compileResult = compileResultByDocker();
        //编译失败
        if (!compileResult.isCompiled()){
            deleteUserCodeFile();//编译失败后删除文件
            dockerSandBoxPool.returnContainer(containerId); //容器放回容器池
            return SandBoxExecuteResult.fail(CodeRunStatus.COMPILE_FAILED,compileResult.getExeMessage());
        }
        //执行代码
        return  executeResultJavaCodeByDocker(inputList);
    }


    //创建并且返回用户代码的文件
    private void createUserCodeFile(String userCode){
        String userCodeDir=dockerSandBoxPool.getCodeDir(containerId);
        userCodeFileName=userCodeDir+File.separator+JudgeConstants.USER_CODE_JAVA_CLASS_NAME;
        //将用户提交的代码(userCode)写入文件(userCodeFileName)中
        String name=dockerSandBoxPool.getContainerNameById(containerId);

        String newUserCodeDir=System.getProperty("user.dir")+File.separator+"usr"+File.separator+"share"+
                File.separator+"java"+File.separator+name+File.separator+JudgeConstants.USER_CODE_JAVA_CLASS_NAME;
        FileUtil.writeString(userCode,newUserCodeDir, Constants.UTF8);
        FileUtil.writeString(userCode,userCodeFileName, Constants.UTF8);
    }


    //编译,使用docker编译
    private CompileResult compileResultByDocker(){
        //DOCKER_JAVAC_CMD当前文件通过数据卷挂载到对应的docker目录下,所以要去对应的目录进行编译
        //编译不需要参数(null)
        //containerId容器id,指定去哪个容器执行
        //完整的编译指令cmdId
        String cmdId=createExeCmd(JudgeConstants.DOCKER_JAVAC_CMD,null,containerId);
        log.info("编译执行的指令为:{}",cmdId);
        //用于获取编译后的结果
        DockerStartResultCallback resultCallback=new DockerStartResultCallback();
        //获取最终结果,编译是否通过以及未通过的错误日志
        CompileResult compileResult=new CompileResult();
        try {
            dockerClient
                    .execStartCmd(cmdId)
                    .exec(resultCallback)
                    .awaitCompletion();
            if (CodeRunStatus.FAILED.equals(resultCallback.getCodeRunStatus())){
                compileResult.setCompiled(false);
                compileResult.setExeMessage(resultCallback.getErrorMessage());
            }else {
                compileResult.setCompiled(true);
            }
            return compileResult;
        }catch (InterruptedException e){
            throw new RuntimeException(e);
        }
    }
    //执行代码
    private SandBoxExecuteResult executeResultJavaCodeByDocker(List<String> inputList) {
        List<String> outputList = new ArrayList<>();//记录输出结果
        long maxMemory = 0L; //最大占用内存
        long maxUseTime = 0L; //最大运行时间
        //执行用户代码
        //因为可能会有多组测试用例,我们都需要执行
        for (String inputArgs : inputList) {
            //cmdId是命令标识,执行命令后会生成一个cmdId,可以定位命令
            String cmdId = createExeCmd(JudgeConstants.DOCKER_JAVA_EXEC_CMD, inputArgs, containerId);
            //开始执行
            StopWatch stopWatch = new StopWatch();             //执行代码后开始计时
            //执行情况监控
            StatsCmd statsCmd = dockerClient.statsCmd(containerId);  //启动监控
            StatisticsCallback statisticsCallback = statsCmd.exec(new StatisticsCallback());   //异步获取资源使用情况
            stopWatch.start();
            // statsCmd.start();
            DockerStartResultCallback resultCallback = new DockerStartResultCallback();
            try {
                dockerClient.execStartCmd(cmdId)                         //cmdId 命令id,execStartCmd就是执行这条命令
                        .exec(resultCallback)                           //resultCallback作用就是拿到执行结果
                        .awaitCompletion(timeLimit, TimeUnit.SECONDS);  //阻塞等待,超过timeLimit时间限制就不会等待
                if (CodeRunStatus.FAILED.equals(resultCallback.getCodeRunStatus())) {
                    return SandBoxExecuteResult.fail(CodeRunStatus.NOT_ALL_PASSED);
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            stopWatch.stop();     //结束计时
            statsCmd.close();     //结束docker容器执行统计
            long userTime = stopWatch.getLastTaskTimeMillis(); //执行耗时
            maxUseTime = Math.max(userTime, maxUseTime);
            Long memory = statisticsCallback.getMaxMemory();
            if (memory != null) {
                maxMemory = Math.max(maxMemory, statisticsCallback.getMaxMemory());  //记录占用最大内存的测试用例
            }
            if (StrUtil.isNotEmpty(resultCallback.getMessage())) {
                outputList.add(resultCallback.getMessage().trim());
            }//记录正确的输出结果
        }

        dockerSandBoxPool.returnContainer(containerId);  //放回容器池
        deleteUserCodeFile();  //清理文件

        return getSanBoxResult(inputList, outputList, maxMemory, maxUseTime); //封装结果
    }


    private SandBoxExecuteResult getSanBoxResult(List<String> inputList, List<String> outList,
                                                 long maxMemory, long maxUseTime) {
        if (inputList.size() != outList.size()) {
            //输入用例数量 不等于 输出用例数量  属于执行异常
            return SandBoxExecuteResult.fail(CodeRunStatus.NOT_ALL_PASSED, outList, maxMemory, maxUseTime);
        }
        return SandBoxExecuteResult.success(CodeRunStatus.SUCCEED, outList, maxMemory, maxUseTime);
    }

    /**
     * 在指定的Docker容器中创建一个可执行命令，并返回该命令的唯一标识 ID。
     * @param javaCmdArr 要执行的命令数组
     * @param inputArgs 要执行的命令数组
     * @param containerId 指定要在哪个容器中执行命令
     * @return 该命令的唯一 ID。
     */
    private String createExeCmd(String[] javaCmdArr, String inputArgs, String containerId) {
        if (!StrUtil.isEmpty(inputArgs)){
            //当入参不为空的时候拼接入参
            String[] inputArray=inputArgs.split(" ");//入参
            javaCmdArr= ArrayUtil.append(JudgeConstants.DOCKER_JAVA_EXEC_CMD,inputArray);
        }
        ExecCreateCmdResponse cmdResponse=dockerClient
                .execCreateCmd(containerId)    //指定执行命令的容器
                .withCmd(javaCmdArr)         //执行的命令是什么
                .withAttachStderr(true)      //开启错误输出获取
                .withAttachStdin(true)        //发送输入数据
                .withAttachStdout(true)       //捕获容器的正常输出
                .exec();
        return cmdResponse.getId();
    }

    //删除文件
    private void deleteUserCodeFile(){
        FileUtil.del(userCodeFileName);
    }

}
